/*
 * Copyright 2008 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.rest.xml;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import net.datajanitor.baja.spi.BoxSpiException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLUtils {
    private static final Log logger = LogFactory.getLog(XMLUtils.class);
    
    private static String printDocument(Node node, int indent) {
        StringBuilder builder = new StringBuilder();
        
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            for (int i = 0; i < indent; i++) {
                builder.append(' ');
            }
            
            builder.append("<").append(node.getNodeName());
            NamedNodeMap attrs = node.getAttributes();
            for (int i = 0, len = attrs.getLength(); i < len; i++) {
                Node attrNode = attrs.item(i);
                if (attrNode != null) {
                    builder.append(' ').append(attrNode.getNodeName()).append("=\"").append(attrNode.getNodeValue()).append("\"");
                }
            }
            builder.append(">");
            
            NodeList children = node.getChildNodes();
            for (int i = 0, len = children.getLength(); i < len; i++) {
                builder.append(printDocument(children.item(i), indent + 2));
            }
            
            for (int i = 0; i < indent; i++) {
                builder.append(' ');
            }
            
            builder.append("</").append(node.getNodeName()).append(">\n");
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            builder.append(node.getTextContent());    
        }
        
        return builder.toString();  
    }
    
    public static Document buildDocument(InputStream input) throws SAXException, IOException, ParserConfigurationException {  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();   
        Document doc = builder.parse(input);

        if (logger.isDebugEnabled()) {
            logger.debug("Built document: " + printDocument(doc));
        }

        return doc;
    }
    
    public static String printDocument(Document doc) {
        StringBuilder builder = new StringBuilder();
        
        Element root = doc.getDocumentElement();
        builder.append(printDocument(root, 0));
        
        return builder.toString();     
    }

    public static NodeList query(Document doc, String query) throws XPathExpressionException {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(query); 
       
        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }
    
    public static String getText(Document doc, String path) throws BoxSpiException {
        String query = path + "/text()";

        try {
            NodeList result = query(doc, query);
            if (result.getLength() == 1) {
                String resultValue = ((Node) result.item(0)).getNodeValue();
                return resultValue;
            } else {
                return null;
            }
        } catch (XPathExpressionException e) {
            throw new BoxSpiException("Error querying response", e);
        }        
    }    
}
